<script setup>
import { ref, onMounted } from 'vue'
import { getHistorySettlement } from '@/api/goodsSettle'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { formatDateTime } from '@/utils/dayjs'
// import ViewHistoryDetails from './components/ViewHistoryDetails.vue' // 稍后创建详情组件

// 单据状态映射 (0:未审批;1:审批中;2:审核通过;3:审核未通过;4:已支付)
const documentStateMap = {
  0: { text: '未审批', type: 'info' },
  1: { text: '审批中', type: 'warning' },
  2: { text: '审核通过', type: 'success' },
  3: { text: '审核未通过', type: 'danger' },
  4: { text: '已支付', type: 'success' },
}

const getDocumentState = (state) => {
  return documentStateMap[state] || { text: '未知状态', type: 'info' }
}

// 列表 & 分页
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 详情弹窗
const detailsDialogVisible = ref(false)
const selectedHistoryItem = ref(null)

// 请求参数
const requestParams = ref({
  currentPage: 1,
  pageSize: 10,
  queryFields: {
    documentNumber: '', // 根据接口文档，使用 documentNumber
  },
})

// 获取数据
const fetchHistoryData = async () => {
  try {
    loading.value = true
    const params = {
      ...requestParams.value,
      queryFields: {
        documentNumber: requestParams.value.queryFields.documentNumber?.trim() || null,
      },
    }
    const res = await getHistorySettlement(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取结算历史失败')
    }
  } catch (error) {
    logger.error('获取结算历史失败', error)
    ElMessage.error('获取结算历史失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  requestParams.value.currentPage = 1
  fetchHistoryData()
}

// 重置
const resetSearch = () => {
  requestParams.value.queryFields.documentNumber = ''
  requestParams.value.currentPage = 1
  fetchHistoryData()
}

// 分页事件
const handleSizeChange = (val) => {
  requestParams.value.pageSize = val
  fetchHistoryData()
}

const handleCurrentChange = (val) => {
  requestParams.value.currentPage = val
  fetchHistoryData()
}

// 查看详情
const handleViewDetails = (row) => {
  selectedHistoryItem.value = row
  detailsDialogVisible.value = true
}

// 挂载
onMounted(() => {
  fetchHistoryData()
})
</script>

<template>
  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="requestParams.queryFields" @submit.prevent="handleSearch">
          <el-form-item label="单据号">
            <el-input
              v-model="requestParams.queryFields.documentNumber"
              placeholder="请输入单据号"
              clearable
              style="width: 240px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" height="100%">
        <el-table-column
          prop="documentNumber"
          label="单据号"
          min-width="180"
          align="center"
          fixed
        />
        <el-table-column
          prop="settlementAmountSum"
          label="结算金额(元)"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="settlementPointsSum"
          label="结算积分"
          min-width="120"
          align="center"
        />
        <el-table-column label="单据状态" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getDocumentState(row.documentState).type">{{
              getDocumentState(row.documentState).text
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="dealer"
          label="商家名称"
          min-width="200"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column prop="nickname" label="申请人" min-width="120" align="center" />
        <el-table-column label="申请时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.requestTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="bank"
          label="开户行"
          min-width="180"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column prop="bankName" label="户名" min-width="120" align="center" />
        <el-table-column prop="bankCode" label="银行卡号" min-width="180" align="center" />
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetails(row)">
              <template #icon>
                <el-icon><LineMdExternalLink /></el-icon>
              </template>
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="requestParams.currentPage"
          v-model:page-size="requestParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog v-model="detailsDialogVisible" title="结算详情" width="720px" destroy-on-close>
      <el-descriptions v-if="selectedHistoryItem" :column="2" border>
        <el-descriptions-item label="单据号">
          {{ selectedHistoryItem.documentNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="单据状态">
          <el-tag :type="getDocumentState(selectedHistoryItem.documentState).type">
            {{ getDocumentState(selectedHistoryItem.documentState).text }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="申请人">
          {{ selectedHistoryItem.nickname }}
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">
          {{ formatDateTime(selectedHistoryItem.requestTime) }}
        </el-descriptions-item>

        <el-descriptions-item label="审核人">
          {{ selectedHistoryItem.adminName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="审核时间">
          {{ formatDateTime(selectedHistoryItem.checkTime) }}
        </el-descriptions-item>

        <el-descriptions-item label="支付人">
          {{ selectedHistoryItem.paymentUser || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">
          {{ formatDateTime(selectedHistoryItem.paymentTime) }}
        </el-descriptions-item>

        <el-descriptions-item label="商家名称">
          {{ selectedHistoryItem.dealer }}
        </el-descriptions-item>
        <el-descriptions-item label="结算金额(元)">
          {{ selectedHistoryItem.settlementAmountSum }}
        </el-descriptions-item>

        <el-descriptions-item label="结算积分">
          {{ selectedHistoryItem.settlementPointsSum }}
        </el-descriptions-item>
        <el-descriptions-item label="支付金额(元)">
          {{ selectedHistoryItem.paymentMoney || '-' }}
        </el-descriptions-item>

        <el-descriptions-item label="开户行">
          {{ selectedHistoryItem.bank }}
        </el-descriptions-item>
        <el-descriptions-item label="户名">
          {{ selectedHistoryItem.bankName }}
        </el-descriptions-item>

        <el-descriptions-item label="银行卡号" :span="2">
          {{ selectedHistoryItem.bankCode }}
        </el-descriptions-item>

        <el-descriptions-item label="审核意见" :span="2">
          {{ selectedHistoryItem.comments || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ selectedHistoryItem.notes || '-' }}
        </el-descriptions-item>
      </el-descriptions>

      <div v-if="selectedHistoryItem?.receipt" class="receipt-container">
        <div class="receipt-label">收据凭证：</div>
        <el-image
          style="width: 160px; height: 160px; border-radius: 8px; overflow: hidden"
          :src="selectedHistoryItem.receipt"
          :preview-src-list="[selectedHistoryItem.receipt]"
          fit="cover"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;
    .el-table {
      flex: 1;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}

.receipt-container {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  align-items: center;
  .receipt-label {
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
  }
}
</style>
